<template>
  <div class="search-suggest">
    <van-cell
      v-for="item in suggestions"
      :key="item.id"
      @click="$emit('search', item)"
      icon="search"
    >
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggections } from '@/api/search.js'
// 导入lodash 防抖动方法
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggest',
  components: {

  },
  props: {
    // 父组件传值给 子组件 接收数据
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      suggestions: [] // 联想到的数据数组
    }
  },
  watch: {
    // 监听searchText变化 防抖处理
    searchText: {
      handler: debounce(function (value) {
        this.loadSearchSuggections(value)
      }, 200),
      immediate: true // 监听立即触发函数
    }
  },
  created () {

  },
  methods: {
    // 加载搜索建议列表
    async loadSearchSuggections (q) {
      try {
        const { data } = await getSearchSuggections(q)
        console.log(data)
        this.suggestions = data.data.options
      } catch (e) {
        this.$toast('获取数据失败，请稍后重试')
      }
    },
    // 匹配搜索关键字改变颜色
    highlight (text) {
      const highlightStr = `<span class="active">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      // text.replace(/匹配的内容/gi, highlightStr)
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggest {
  /deep/.active {
    color: #3296fa;
  }
}
</style>
